const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer()
server.on('request', (req, res) => {
  console.log('url:' + req.url)
  console.log('method' + req.method)
  console.log('some one vist our web server')
  const url = req.url
  let content = ''
  if (url == '/' || url == 'index') {
    content = `<h1 style="color:red">首页</h1>`
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end(content)
  } else if (req.url == 'about') {
    content = 'hello world 我乱码了' + url + req.method
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end(content)
  } else {
    const p = path.join(__dirname, url)
    fs.readFile(p, 'utf-8', (err, dataStr) => {
      if (err) {
        content = `<h1>404 not found</h1>`
      } else {
        content = dataStr
      }
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      res.end(content)
      return
    })
  }
})

server.listen(8080, () => {
  console.log('server running at http://127.0.0.1:8080')
})
